/**
 * Created by DELL on 2018/9/6.
 */
;(function () {
  // 初始化游戏
  // game.init();
  var game = window.game = {
    width: 0,
    height: 0,
    // key_index: 0,  // 第几个音符
    last_key_index: -1,  // 上次点击的是第几个音符
    continue_num: 0,  // 连续点击 次数
    asset: null,
    stage: null,
    ticker: null,
    state: null,
    score: 0,
    bg: null,
    ground: null,
    keyboard: null,  // 按键容器
    gameReadyScene: null,
    gameOverScene: null,
    bgAudio: null,     // bg音乐
    batTime: 865,       // 1拍对应的时长 毫秒
    keyBaseHeight: 600, // 按键基础长度 1拍 按键为1200 短键（小于1拍）长度为300
    // 曲谱
    notation: song3,
    startTime: 0, // 游戏开始时间
    record: [],  // 按键记录
    init: function () {
      // 微信长按出现复制按钮
      document.oncontextmenu = function (e) {
        e.preventDefault();
      };
      this.asset = new game.Asset();
      this.asset.on('complete', function (e) {
        this.asset.off('complete');
        this.initStage();
        this.initEvent();
      }.bind(this));
      this.asset.load();
    },
    initEvent: function () {


      // 返回首页

      this.backBtn.on(Hilo.event.POINTER_START, this.onBackClick.bind(this));
      this.backBtn.on(Hilo.event.POINTER_END, this.onBackEnd.bind(this));
    },
    initStage: function () {
      this.width = Math.min(innerWidth, 450) * 2;
      // this.height = Math.min(innerHeight, 750) * 2;
      this.height = innerHeight * 2;
      this.scale = 0.5;

      //舞台画布
      var renderType = location.search.indexOf('dom') != -1 ? 'dom' : 'canvas';

      //舞台
      this.stage = new Hilo.Stage({
        renderType: renderType,
        width: this.width,
        height: this.height,
        scaleX: this.scale,
        scaleY: this.scale
      });
      this.keyBaseHeight = this.height / 2;
      document.querySelector('.page3').appendChild(this.stage.canvas);

      //启动计时器
      this.ticker = new Hilo.Ticker(60);
      this.ticker.addTick(Hilo.Tween);
      this.ticker.addTick(this.stage);
      this.ticker.start(true);


      //绑定交互事件
      this.stage.enableDOMEvent(Hilo.event.POINTER_START, true);
      this.stage.enableDOMEvent(Hilo.event.POINTER_END, true);
      // this.stage.on(Hilo.event.POINTER_START, this.onUserInput.bind(this));
      //舞台更新
      this.stage.onUpdate = this.onUpdate.bind(this);
      //初始化
      this.initBackground();

      this.initScenes();
      this.initCurrentScore();

      this.initKeyboard();

      this.initScoreAnimate();
      //准备游戏
      this.gameReady();
    },
    // 初始化按键容器
    initKeyboard: function () {
      this.keyboard = new game.Keyboard({
        id: 'keyboard',
        stageHeight: this.height,
        stageWidth: this.width,
      }).addTo(this.stage, 1);
    },
    initScenes: function () {
    },
    onUserInput: function (e) {
      // if (this.state !== 'over' && !this.gameOverScene.contains(e.eventTarget)) {
      //启动游戏场景
      if (this.state === 'ready') this.gameStart();

      //控制小鸟往上飞
      // this.bird.startFly();
      // }
    },
    onUpdate: function (delta) {
    },
    // 更新分数
    updataScore: function (key_index) {
      this.score = this.score + 1;
      this.currentScore.setText(this.score);
      if (key_index === this.last_key_index + 1) {
        // 连续点击
        this.continue_num = this.continue_num + 1;
      } else {
        this.continue_num = 1;
      }
      this.last_key_index = key_index;
      // 分数提示
      this.checkScoreTips(this.continue_num);
    },
    // 特定分数有提示
    checkScoreTips: function (continue_num) {
      // console.log('连续点中数目： ' + continue_num);
      var base_num = 10;
      var continue_ten = continue_num / base_num;
      if (continue_ten === 1) {
        console.log('连续点击10个');
        this.scoreAnimate(0);
      } else if (continue_ten === 2) {
        this.scoreAnimate(1);
        console.log('连续点击20个');
      } else if (continue_ten >= 3 && continue_num % base_num === 0) { // 大于30的整分数 出现完美
        this.scoreAnimate(2);
      }
    },
    // 分数动画
    scoreAnimate: function (type) {
      var _this = this;
      var target = null;
      if (type === 0) {
        target = this.word3;
      } else if (type === 1) {
        target = this.word2;
      } else if (type === 2) {
        target = this.word1;
      }
      if (!target) {
        return false;
      }
      this.scoreTween = new Hilo.Tween(target, null, {}, {
        onComplete: function () {
          _this.currentScore.visible = false;
          setTimeout(function () {
            target.alpha = 0;
            _this.currentScore.visible = true;
          }, 400);
        }
      });
      this.scoreTween.duration = 400;
      this.scoreTween.setProps({
        y: 300,
        alpha: 0,
        scaleX: 0.8,
        scaleY: 0.8,
        x: this.width - this.asset.word1.width * 0.8 >> 1
      }, {
        y: 170, alpha: 1, scaleX: 1, scaleY: 1, x: this.width - this.asset.word1.width >> 1
      });

      this.scoreTween.start();

    },
    // 初始化分数动画
    initScoreAnimate: function () {

      var x = this.width - this.asset.word1.width >> 1;
      var y = 180;
      this.word1 = new Hilo.Bitmap({
        id: 'word1',
        image: this.asset.word1,
        alpha: 0,
        x: x,
        y: y,
      }).addTo(this.stage);

      this.word2 = new Hilo.Bitmap({
        id: 'word2',
        image: this.asset.word2,
        alpha: 0,
        x: x,
        y: y
      }).addTo(this.stage);

      this.word3 = new Hilo.Bitmap({
        id: 'word3',
        image: this.asset.word3,
        alpha: 0,
        x: x,
        y: y
      }).addTo(this.stage);

      // this.scoreTween2 = new Hilo.Tween(this.word2, {}, {});
      // this.scoreTween3 = new Hilo.Tween(this.word3, {}, {});
    },
    // 保存记录
    keepRecord: function (item) {
      var current_time = new Date().getTime(); // ms
      var time_point = current_time - this.startTime;

      this.record.push({
        start_time: time_point,
        note: item.note,
        tone: item.tone,
      });
    },
    initBackground: function () {
      //背景
      var bgImg = this.asset.bg;
      var curtains = this.asset.curtains;
      this.bg = new Hilo.Bitmap({
        id: 'bg',
        image: bgImg,
        scaleX: this.width / bgImg.width,
        scaleY: this.height / bgImg.height
      }).addTo(this.stage);

      // 窗帘
      this.curtains = new Hilo.Bitmap({
        id: 'curtains',
        image: curtains,
        width: this.width,
        scaleX: this.width / curtains.width,
        x: 0,
        y: 0
      }).addTo(this.stage);


      // 四个分割线

      for (var i = 0; i < 4; i++) {
        new Hilo.View({
          id: 'line' + i,
          y: 0,
          x: this.width / 4 * (i + 1) - 1,
          width: 2,
          height: this.height,
          background: 'rgba(255,255,255, 0.3)',
        }).addTo(this.stage);
      }

      var backBtn = this.asset.backBtn;
      // 返回按钮
      this.backBtn = new Hilo.Bitmap({
        id: 'backBtn',
        image: backBtn,
        x: 0,
        y: 78
      }).addTo(this.stage);

      //设置地面的y轴坐标
      // this.ground.y = this.height - this.ground.height;

    },
    initCurrentScore: function () {
      //当前分数
      this.currentScore = new Hilo.BitmapText({
        id: 'score',
        // glyphs: this.asset.numberGlyphs,
        glyphs: this.asset.number2Glyphs,
        textAlign: 'center'
      }).addTo(this.stage, 20);

      //设置当前分数的位置
      this.currentScore.x = this.width - this.currentScore.width >> 1;
      this.currentScore.y = 180;
    },
    // 返回首页点击事件
    onBackClick: function () {
      this.backBtn.alpha = 0.5;
    },
    // 返回事件点击完成；
    onBackEnd: function () {
      this.backBtn.alpha = 1;

      this.gameStop();
    },
    gameReady: function () {
      this.state = 'ready';
      this.score = 0;
      this.score = 0;
      this.last_key_index = -1;
      this.continue_num = 0;
      this.currentScore.visible = true;
      this.currentScore.setText(this.score);
      this.keyboard.init();
    },
    gameStart: function () {
      this.bgAudio.currentTime = 0;
      // this.bgAudio.currentTime = 5.7;
      // this.bgAudio.currentTime = 69;
      // this.bgAudio.currentTime = 13.2;

      this.bgAudio.play();

      this.score = 0;
      this.last_key_index = -1;
      this.continue_num = 0;
      this.state = 'playing';

      this.currentScore.visible = true;
      this.currentScore.setText(this.score);

      this.record = []; // 重置记录
      this.startTime = new Date().getTime();
      this.keyboard.startMove();
    },
    // 游戏暂停
    gameStop: function () {
      this.keyboard.stopMove();
      this.bgAudio.pause();
      window.app.showSongList()
    },
    gameOver: function () {
      if (this.state !== 'over') {
        //设置当前状态为结束over
        this.state = 'over';
        //隐藏屏幕中间显示的分数
        this.currentScore.visible = false;
        //显示结束场景
        app.showGameEnd();
        this.bgAudio.pause();
      }
    }
  }
})();